package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVerifyCode(String phone, String code) {
        ValueOperations<String, String> stringStringValueOperations = template.opsForValue();

        String key = RedisKeys.VERIFY_CODE.join(phone);

        stringStringValueOperations.set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String getVerifyCode(String phone) {
        ValueOperations<String, String> stringStringValueOperations = template.opsForValue();

        String key = RedisKeys.VERIFY_CODE.join(phone);

        return stringStringValueOperations.get(key);
    }

    @Override
    public String setToken(UserInfo userInfo) {

        String token = UUID.randomUUID().toString().replaceAll("-", "");

        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);

        String value = JSON.toJSONString(userInfo);

        // 设置有效期
        template.opsForValue().set(key, value, RedisKeys.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);

        return token;
    }

    @Override
    public UserInfo getUserByToken(String token) {
        if (!StringUtils.hasText(token)) {
            return null;
        }
        String key = RedisKeys.USER_LOGIN_TOKEN.join(token);

        if (template.hasKey(key)) {
            String userStr = template.opsForValue().get(key);
            UserInfo userInfo = JSON.parseObject(userStr, UserInfo.class);
            // 重置token的有效期 登录有效期
            template.expire(key, RedisKeys.USER_LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
            return userInfo;
        }
        return null;
    }

}